<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoledialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="rolesList" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom']"
              v-for="item1 in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="delRolesItem(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="['bdbottom']"
                  v-for="item2 in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="9">
                    <el-tag
                      type="success"
                      closable
                      @close="delRolesItem(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                  </el-col>
                  <el-col :span="10">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="delRolesItem(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="260px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="editRoleInfo(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-search"
              size="mini"
              @click="delFormRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-search"
              size="mini"
              @click="setRightsDialog(scope.row)"
              >分配</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="setRightsdialogVisible"
      width="45%"
      @close="setRightDialogClosed"
    >
      <el-scrollbar style="overflow: hidden; height: 400px; width: 100%">
        <el-tree
          :data="treeRighetsdata"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defKeys"
          ref="treeRef"
          check-on-click-node
        ></el-tree>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesRight">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoledialogVisible"
      width="45%"
      @close="addRoleDialogClosed"
    >
      <el-form
        :model="roleForm"
        :rules="roleFormRules"
        ref="roleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleFrom">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoledialogVisible"
      width="45%"
      @close="editRoleDialogClosed"
    >
      <el-form
        :model="editRoleForm"
        :rules="editrRoleFormRules"
        ref="editRoleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色id" prop="id">
          <el-input v-model="editRoleForm.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditRoleFrom">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      setRightsdialogVisible: false,
      treeRighetsdata: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      roleForm: { roleName: "", roleDesc: "" },
      defKeys: [],
      roleId: "",
      addRoledialogVisible: false,
      editRoledialogVisible: false,
      editRoleForm: {},
      roleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 15, message: "字符长度在6-15之间", trigger: "blur" },
        ],
      },
      editrRoleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 15, message: "字符长度在3-15之间", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("/roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
      console.log(this.rolesList);
    },
    async delRolesItem(roles, ringhtId) {
      const constrm = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "删除提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (constrm !== "confirm") {
        this.$message.info("取消了删除！");
      }

      const { data: res } = await this.$http.delete(
        `roles/${roles.id}/rights/${ringhtId}`
      );

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }

      roles.children = res.data;
    },
    async setRightsDialog(role) {
      //查询所有的权限列表
      const { data: res } = await this.$http.get("rights/tree");

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.treeRighetsdata = res.data;

      this.getLeafKeys(role, this.defKeys);
      //弹出分配框
      this.setRightsdialogVisible = true;
      this.roleId = role.id;
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    setRightDialogClosed() {
      this.defKeys = [];
    },
    //保存设置的权限
    async saveRolesRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const keyid = keys.join(",");
      console.log(keyid);
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: keyid }
      );
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.getRolesList();
      this.setRightsdialogVisible = false;
    },
    //添加角色
    saveRoleFrom() {
      this.$refs.roleFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("校验失败");
        const { data: res } = await this.$http.post("/roles", this.roleForm);
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.addRoledialogVisible = false;
        this.getRolesList();
      });
    },
    addRoleDialogClosed() {
      this.$refs.roleFormRef.resetFields();
    },
    /* 编辑角色 */
    async editRoleInfo(id) {
      this.editRoledialogVisible = true;
      const { data: res } = await this.$http.get("/roles/" + id);
      if (res.meta.status !== 200) return this.$message.error("查询角色失败！");
      this.editRoleForm = res.data;
    },

    /* 编辑角色信息 */
    saveEditRoleFrom() {
      this.$refs.editRoleFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "/roles/" + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("角色修改成功！");
        this.editRoledialogVisible = false;
        this.getRolesList();
      });
    },
    /* 重置编辑样式 */
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields();
    },
    /* 删除角色 */
    async delFormRole(id) {
      const confirmResult = await this.$confirm(
        "此操作将永远删除该数据，是否继续？",
        "删除提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除！");
      }
      const { data: res } = await this.$http.delete("/roles/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除失败！");
      this.$message.success("删除成功！");
      this.getRolesList();
    },
  },
};
</script>
<style lang="less" scoped>
.el-row {
  margin-bottom: 15px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}
.el-tag {
  margin-left: 60px;
  margin-bottom: 10px;
}
.el-scrollbar__wrap {
  overflow: hidden !important;
  padding-bottom: 30px !important;
}
/deep/.el-dialog__body {
  padding: 10px 20px;
}
/deep/.el-scrollbar__wrap {
  overflow-x: hidden;
}

/deep/ .el-scrollbar__view {
  overflow-x: hidden;
}
</style>
